var canvas=document.getElementById("box");
var w=canvas.width=window.innerWidth;
var h=canvas.height=window.innerHeight;
var ctx=canvas.getContext("2d");
canvas.onmousemove=function (e) {
    var e=e||window.event;
    mouse.x=e.clientX;
    mouse.y=e.clientY;
}
canvas.onmouseleave=function (){
    mouse={};
}


var num=200;

var data=[];
var mouse={};

for (let i = 0; i < num; i++) {
    data[i]={
        x:Math.random()*w,
        y:Math.random()*h,
        xSpeed:Math.random()*0.7-0.35,
        ySpeed:Math.random()*0.7-0.35,
    }
    // Circle(data[i].x,data[i].y);
}
function Circle(x,y) {
    ctx.save();
    ctx.fillStyle='white';
    ctx.beginPath();
    ctx.arc(x,y,0.5,0,2*Math.PI,false);
    ctx.closePath();
    ctx.fill();
    ctx.restore();
}
(function Move() {
    ctx.clearRect(0,0,w,h);
    for (let i = 0; i < num; i++) {
        data[i].x+=data[i].xSpeed;
        data[i].y+=data[i].ySpeed;
        if(data[i].x>w||data[i].x<=0){
            data[i].xSpeed=-data[i].xSpeed;
        }
        if(data[i].y>w||data[i].y<=0){
            data[i].ySpeed=-data[i].ySpeed;
        }
        // Circle(data[i].x,data[i].y);
        for (let j = 0; j < num; j++) {
            line(data[i].x,data[i].y,data[j].x,data[j].y,80,'greenyellow');
            if(mouse.x){
                line(mouse.x,mouse.y,data[j].x,data[j].y,80,'blue');
            }
        }
    }
    var t=window.requestAnimationFrame(Move);
})();
function line(x1, y1, x2, y2, dis, color) {
    if(Math.pow(x2-x1,2)+Math.pow(y2-y1,2)<=Math.pow(dis,2)){
        ctx.save();
        var lin=ctx.createLinearGradient(x1,y1,x2,y2);
        lin.addColorStop(0,'blue');
        lin.addColorStop(0.5,"red")
        lin.addColorStop(1,color);
        ctx.beginPath();
        ctx.strokeStyle=lin;
        ctx.moveTo(x1,y1);
        ctx.lineTo(x2,y2);
        ctx.stroke();
        ctx.closePath();
        ctx.restore();

    }
}